import random
import requests
import json
import time

# 模拟请求地址
url = "http://localhost:8080/rule/save"

# 请求头
headers = {
    "Content-Type": "application/json"
}

# 可选逻辑关系描述
logic_descriptions = ["全都满足", "任意满足", "都不满足"]

# 生成随机规则名称
def generate_random_name():
    prefixes = ["规则A", "策略B", "配置C", "测试D", "动态E"]
    suffixes = ["v1", "v2", "alpha", "beta", "final"]
    return f"{random.choice(prefixes)}_{random.choice(suffixes)}"

# 生成随机数据值
def generate_random_data_value():
    return round(random.uniform(0, 200), 2)

# 发送 POST 请求
def send_save_request(params):
    try:
        response = requests.post(url, data=json.dumps(params), headers=headers, timeout=5)
        return response.status_code, response.text
    except requests.exceptions.RequestException as e:
        return 500, str(e)

if __name__ == "__main__":
    total = 1000
    success_count = 0
    fail_count = 0

    print(f"开始循环调用 /rule/save 接口 {total} 次...\n")

    for i in range(1, total + 1):
        # 构建随机参数
        params = {
            "name": generate_random_name(),
            "data": generate_random_data_value(),
            "logicDesc": random.choice(logic_descriptions),
            "conditionNum": random.randint(1, 5)  # 随机选择 1~5 个条件
        }

        status_code, response_text = send_save_request(params)

        if status_code == 200:
            success_count += 1
            print(f"[{i}/{total}] 成功 | 状态码: {status_code}")
        else:
            fail_count += 1
            print(f"[{i}/{total}] 失败 | 状态码: {status_code} | 错误信息: {response_text}")

        # 控制请求频率（防止服务器压力过大）
        time.sleep(0.05)

    print("\n调用完成！")
    print(f"总请求数: {total}")
    print(f"成功次数: {success_count}")
    print(f"失败次数: {fail_count}")
